package com.sz.zhiling.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sz.zhiling.mapper.TCityMapper;
import com.sz.zhiling.model.PageBean;
import com.sz.zhiling.model.TCity;
import com.sz.zhiling.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service//注入Dao
public class CityServiceImpl implements ICityService {

    @Autowired
    private TCityMapper tCityMapper;

    //分页查询所有城市
    @Override
    public PageBean<TCity> getAllCity(int index, int size) {
        //分页方法
        PageHelper.startPage(index,size);
        List<TCity> list = tCityMapper.selectAll();//查询所有
        Page<TCity> plist = (Page<TCity>) list;
        PageBean<TCity> pb = new PageBean<>(
                //写入PageBean中参数
                plist.getTotal(),
                plist.getResult(),
                plist.getPageSize(),
                plist.getPages(),
                plist.getPageNum()
        );
        return pb;
    }

    //删除城市
    @Override
    public void deleteCity(int cid) {
        tCityMapper.deleteByPrimaryKey(cid);
    }

    //查询所有的省
    @Override
    public List<TCity> getAllProvinces() {
        //查询所有省fid=0
        Example example = new Example(TCity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("fId",0);
        return tCityMapper.selectByExample(example);
    }

    //搜索城市
    @Override
    public PageBean<TCity> searchAllCity(int i, int i1, TCity tCity) {
        PageHelper.startPage(i,i1);//开始分页
        Example example = new Example(TCity.class);
        Example.Criteria criteria = example.createCriteria();
        if(tCity != null){
           if(tCity.getcId()!=null && tCity.getcId()>0){
               criteria.andEqualTo("cId",tCity.getcId());//根据cid查询
           }
           if(tCity.getfId()!=null && tCity.getfId()>0){
               criteria.andEqualTo("fId",tCity.getfId());//根据fid查询
           }
           if(null != tCity.getcName() && !"".equals(tCity.getcName())){
               criteria.andLike("cName","%"+tCity.getcName()+"%");//根据名字查询,模糊查询
           }
        }
        List<TCity> list = tCityMapper.selectByExample(example);
        Page<TCity> plist = (Page<TCity>) list;
        PageBean<TCity> pb = new PageBean<>(
                //写入PageBean中参数
                plist.getTotal(),
                plist.getResult(),
                plist.getPageSize(),
                plist.getPages(),
                plist.getPageNum()
        );
        return pb;
    }

    @Override
    public void updateCity(TCity tCity) {
        tCityMapper.updateByPrimaryKey(tCity);
    }

    @Override
    public void addCity(TCity tCity) {
        tCityMapper.insert(tCity);
    }

    @Override
    public TCity getCityByCid(int cId) {
        return tCityMapper.selectByPrimaryKey(cId);
    }
}
